package com.neu.cloudfactory.service.imp;

import com.neu.cloudfactory.bean.Factory.Factory;
import com.neu.cloudfactory.bean.Login.LoginDTO;
import com.neu.cloudfactory.bean.Login.LoginVO;
import com.neu.cloudfactory.bean.Login.Result;
import com.neu.cloudfactory.bean.User.User;
import com.neu.cloudfactory.repository.FactoryRepository;
import com.neu.cloudfactory.repository.UserRepository;
import com.neu.cloudfactory.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FactoryRepository factoryRepository;

    @Override
    public Result login(LoginDTO loginDTO) {
        if (StringUtils.isEmpty(loginDTO.getAccount())){
            return new Result(400,"账号不能为空","");
        }
        if (StringUtils.isEmpty(loginDTO.getPassword())){
            return new Result(400,"密码不能为空","");
        }
        //通过登录名查询用户
        User user=userRepository.findByAccount(loginDTO.getAccount()).get();
        //比较密码
        if (user!=null&&user.getPassword().equals(loginDTO.getPassword())){
            LoginVO loginVO=new LoginVO();
            loginVO.setId(user.getId());
            //这里token直接用一个uuid
            //使用jwt的情况下，会生成一个jwt token,jwt token里会包含用户的信息
            loginVO.setToken(UUID.randomUUID().toString());
            loginVO.setUser(user);
            if(user.getTypeid()==1){
                Factory factory = factoryRepository.findByManagerid(user.getId());
                loginVO.setFactoryid(factory.getId());
                loginVO.setFactorystatusid(factory.getStatusid());
            }else {
                loginVO.setFactoryid(0);
            }
            return new Result(200,"",loginVO);
        }
        return new Result(401,"登录失败","");
    }
}
